<template>
  <view>
    <view :prop="customKeyMap" :change:prop="tv.propChanged" @click="tv.click" id="tvClick"></view>
    <slot></slot>
  </view>
</template>

<script>
  /**
   * tv-page tv页面
   * @description 类似于page，声明一个TV端页面，包含按键监听、参数配置等核心功能
   * @property { options } 配置
   * @property { customKeyMap } 自定义按键映射
   */
  export default {
    props: {
      // 配置
      options: {
        type: Object,
        default: () => {}
      },
      // 自定义按键映射
      customKeyMap: {
        type: Object,
        default: () => {}
      }
    },
    provide() {
      return {
        tvProps: this.tvProps
      };
    },
    data: () => ({
      tvProps: {
        tvFocus: [], // 可获取焦点元素集
        keyType: '', // 按键类型
        areaIndex: 0, // 默认焦点区域索引
        preventDefault: false, // 阻止默认事件
        debugger: false // 显示调试信息
      }
    }),
    watch: {
      options: {
        immediate: true,
        handler(val) {
          Object.assign(this.tvProps, val);
        }
      }
    },
    methods: {
      // 按键事件
      keyClick({ keyType, keyCode }) {
        this.tvProps.debugger && uni.showToast({
          title: `按键类型：${keyType}，按键编码：${keyCode}`,
          icon: 'none',
          duration: 2000
        });
        this.tvProps.keyType = keyType;
        this.tvProps.tvFocus[this.tvProps.areaIndex].tvViews[this.tvProps.tvFocus[this.tvProps.areaIndex].index].viewKeyClick(keyType);
      }
    }
  };
</script>

<script module="tv" lang="renderjs">
  import { keyMap } from '../../config/index.js'
  export default {
    data() {
      return {
        keyMap
      }
    },
    methods: {
      // 监听按键
      watchKeyDown(e) {
        const keyCode = e.keyCode || e.which;
        this.keyCode = keyCode;
        this.keyType = Object.keys(this.keyMap).find(v => this.keyMap[v].includes(keyCode));
        this.keyType && document.querySelector('#tvClick').click();
      },
      // 传递事件到service层
      click(event, ownerInstance) {
        // 调用 service 层的方法
				ownerInstance.callMethod('keyClick', { keyType: this.keyType, keyCode: this.keyCode});
      },
      // 接收视图层参数
      propChanged(e) {
        Object.assign(this.keyMap, e);
      }
    },
    mounted() {
      window.addEventListener('keydown', this.watchKeyDown);
    },
    destroyed() {
      window.removeEventListener('keydown', this.watchKeyDown);
    },
    activated() {
      window.addEventListener('keydown', this.watchKeyDown);
    },
    deactivated() {
      window.removeEventListener('keydown', this.watchKeyDown);
    }
  }
</script>
